package com.jsoft.jsofted.platform.vo;

import com.jsoft.jsofted.platform.entity.MenuEntity;

import java.util.*;

public class MenuTreeMaker {
    private List<MenuEntity> entityList;

    private LinkedHashMap<Long, MenuBean> nodes;

    private List<MenuBean> tree;

    private MenuTreeMaker(List<MenuEntity> list) {
        this.entityList = list;
    }

    public static List<MenuBean> make(List<MenuEntity> list) {
        MenuTreeMaker maker = new MenuTreeMaker(list);
        maker._makeNodes();
        maker._makeTree();
        return maker.tree;
    }

    public static List<MenuBean> makeActionsTree(List<MenuEntity> list) {
        MenuTreeMaker maker = new MenuTreeMaker(list);
        maker._makeNodes();
        maker._makeTree();
        maker._makeActions();
        return maker.tree;
    }

    private void _makeNodes() {
        this.nodes = new LinkedHashMap();
        for (MenuEntity entity : entityList) {
            MenuBean node = new MenuBean();
            node.copyFrom(entity);
            this.nodes.put(entity.getId(), node);
        }
    }

    private void _makeTree() {
        this.tree = new LinkedList();
        for (MenuEntity entity : entityList) {
            MenuBean node = this.nodes.get(entity.getId());
            MenuBean parentNode = this.nodes.get(node.getParentId());

            if (parentNode == null) { // 当前节点为根节点
                this.tree.add(node);
            } else { // 当前节点为子节点
                parentNode.addChild(node);
            }
        }
    }

    private void _makeActions() {
        for (MenuEntity entity : entityList) {
            MenuBean menuNode = this.nodes.get(entity.getId());

            List<Map> actions = entity.getActions();
            if (actions == null || actions.size() == 0) {
                continue;
            }
            for(Map<String,String> action: actions) {
                String key = action.get("code");
                String title = action.get("name");

                MenuBean actionNode = new MenuBean();
                actionNode.setKey(menuNode.getKey()+":"+key);
                actionNode.setTitle(title);

                menuNode.addChild(actionNode);
            }
        }
    }

}
